package com.android.happymall.fragment.group;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.happymall.R;
import com.android.happymall.activity.GoodsDetailActivity;
import com.android.happymall.adapt.MyDateViewHolder;
import com.android.happymall.fragment.BaseLazyFragment;
import com.android.happymall.model.auction.AuctionRecentlyOrder;
import com.android.happymall.model.auction.AuctionRecentlyOrderCallback;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.HttpUtils;
import com.android.happymall.utils.ObjectUtils;
import com.android.happymall.view.CustomViewpager;
import com.android.happymall.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/10/23.
 */

public class Fragment_PastedTurnover extends BaseLazyFragment {


    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;

    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    private FragmentActivity mcontext;
    private View view;
    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    private boolean networkConnected;
    private AdaptList adapter;
    private ArrayList<AuctionRecentlyOrder.DataBean.ListBean> listdata  = new ArrayList<>();;
    private CustomViewpager viewpager;
    private GoodsDetailActivity mActivity;
    private int position;
    private int page =1;
    private int lastposition =0;
    private String auction_id;
    /**
     * 最新成交
     */

    public void  SecurityInfoFragment(CustomViewpager viewpager,int position,String auction_id)
    {
        this.position = position;
        this.viewpager = viewpager;
        this.auction_id = auction_id;
    }
    public Fragment_PastedTurnover() {


    }

    public static Fragment_PastedTurnover newInstance() {
        Fragment_PastedTurnover fragment = new Fragment_PastedTurnover();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (GoodsDetailActivity) activity;
        mActivity.setHandler(mHandler);
    }
    public Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    page = page+1;
                    GetDataListData();
                    break;
            }
        };

    };

    @Override
    protected void initPrepare() {

        ReFreshData();
    }

    private void initRecycle() {
        adapter = new AdaptList(mcontext, listdata,"");
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent = new Intent(mcontext, GoodsDetailActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW,2);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID,listdata.get(position).getId());
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_COMMON_ID,"");
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {

        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {

            GetDataListData();
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }

    }


    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_recycle_pastedturnover, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        viewpager.setObjectForPosition(view,position);initRecycle();
        return view;
    }

    private void ReFreshData() {

    }


    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        GetDataListData();


    }





    /**
     * 商品列表
     */
    private void GetDataListData() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        final String address = ConstantsUrl.domain + ConstantsUrl.ACUTIONRECENTLYORDER ;
        HashMap<String,String> map = new HashMap<>();
        map.put("page",page+"");
        map.put("size","4");
        map.put("auction_id",auction_id);
        if (networkConnected) {

            HttpUtils.get(address,map, new AuctionRecentlyOrderCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mActivity.notifyFinish();
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(AuctionRecentlyOrder response, int id) {

                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        listdata = new ArrayList<>();
                        if (response.getData().getList() != null&&response.getData().getList().size()>0) {

                            for (int i = 0; i < response.getData().getList().size(); i++) {
                                listdata.add(new AuctionRecentlyOrder.DataBean.ListBean(AuctionRecentlyOrder.DataBean.ListBean.THREE, response.getData().getList().get(i).getId()
                                        , response.getData().getList().get(i).getC_time(), response.getData().getList().get(i).getThumb()
                                        ,  response.getData().getList().get(i).getPhoto(),response.getData().getList().get(i).getMid(), response.getData().getList().get(i).getPay_time()
                                        , response.getData().getList().get(i).getMarket_price(), response.getData().getList().get(i).getPrice()
                                        , response.getData().getList().get(i).getMid_coin_count(), response.getData().getList().get(i).getUsername()
                                        , response.getData().getList().get(i).getReturns_score(),response.getData().getList().get(i).getMid_count()
                                        ,response.getData().getList().get(i).getSafe_price(),response.getData().getList().get(i).getSafe_rate()
                                        ,response.getData().getList().get(i).getSafe_end(),response.getData().getList().get(i).getTop_price()
                                        ,response.getData().getList().get(i).getTop_end()));
                            }
                            adapter.addData(lastposition,listdata);
                            lastposition = lastposition+response.getData().getList().size();
                            mActivity.notifyFinish();

                        } else {
                            mActivity.notifyFinish();

                        }
                    }
                }
            });
        }else {
            noData.setVisibility(View.VISIBLE);
            noDataTv.setVisibility(View.VISIBLE);
            ObjectUtils.toast(mcontext, "网络未连接");

        }
    }


    public class AdaptList extends BaseMultiItemQuickAdapter<AuctionRecentlyOrder.DataBean.ListBean,MyDateViewHolder> {
        private String type;
        private FragmentActivity mcontext;
        private int limitposition;

        public AdaptList(FragmentActivity context, List<AuctionRecentlyOrder.DataBean.ListBean> data, String type) {
            super(data);
            this.mcontext = context;
            this.type = type;
            addItemType(AuctionRecentlyOrder.DataBean.ListBean.THREE, R.layout.item_detail_pastturnover);
        }



        @Override
        protected void convert(MyDateViewHolder holder, AuctionRecentlyOrder.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case AuctionRecentlyOrder.DataBean.ListBean.THREE:

                    //判断list里面是否含有该holder，没有就增加
                    //因为list已经持有holder的引用，所有数据自动会改变
                    int time = Integer.parseInt(mainlistdata.getC_time());
                    long msl=(long)time*1000;
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String text = format.format(msl);
                    holder.setText(R.id.recently_day,text);
                    ObjectUtils.photoCircle(mContext, mainlistdata.getPhoto(), ((ImageView) holder.getView(R.id.item_detail_pastturnoverimg)));
                    holder.setText(R.id.aishang_username, mainlistdata.getUsername());
                    holder.setText(R.id.aishang_marketprice, mainlistdata.getPrice());
                    float percent = (Float.parseFloat(mainlistdata.getPrice())/Float.parseFloat( mainlistdata.getMarket_price()))*100;
                    percent = 100-percent;
                    if(percent>95)
                    {
                        holder.setText(R.id.aishang_savepercent,"99.95%");
                    }
                    else
                    {
                        DecimalFormat decimalFormat=new DecimalFormat(".00");
                        String aishang_savepercent =  decimalFormat.format(percent);
                        holder.setText(R.id.aishang_savepercent, aishang_savepercent);
                    }


                    break;

            }
        }


    }
}
